package com.youlai.system.plugin.easyexcel;

import com.alibaba.excel.context.AnalysisContext;
import com.youlai.system.model.entity.AssetComputer;
import com.youlai.system.model.entity.SysUser;
import com.youlai.system.model.vo.AssetComputerImportVO;
import com.youlai.system.security.util.SecurityUtils;
import com.youlai.system.service.AssetComputerService;
import com.youlai.system.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


public class ComputerImportLisenter extends MyAnalysisEventListener<AssetComputerImportVO>{
    private final List<SysUser> sysUsers;
    private final List<AssetComputer> assetComputerList;
    private List<AssetComputerImportVO> assetComputerImportVOList = new ArrayList<>();
    private StringBuilder tags = new StringBuilder();
    private AssetComputerService assetComputerService;
    private long successCount = 0;
    public ComputerImportLisenter(List<SysUser> sysUsers, List<AssetComputer> assetComputerList, AssetComputerService assetComputerService)  {
        this.sysUsers = sysUsers;
        this.assetComputerList = assetComputerList;
        this.assetComputerService= assetComputerService;
    }

    @Override
    public String getMsg() {
        return "成功导入了"+ successCount  + "电脑数据，标签重复导入失败有" + tags ;
    }

    @Override
    public void invoke(AssetComputerImportVO assetComputerImportVO, AnalysisContext analysisContext) {
        // 检查当前导入的用户名是否正确
        String username = assetComputerImportVO.getUsername();
        String tag = assetComputerImportVO.getTag();
        // 用户id
        Long userId = 1L;
        // 是否存在相同数据
        boolean flag = false;
        for (SysUser sysUser : sysUsers) {
            if (sysUser.getUsername().equals(username)) {
                // 用户名存在
                userId = sysUser.getId();
                break;
            }

        }
        for (AssetComputer assetComputer : assetComputerList) {
           if (assetComputer.getTag().equals(tag)) {
               flag = true;
           }
        }
        for (AssetComputerImportVO computerImportVO : assetComputerImportVOList) {
            if (computerImportVO.getTag().equals(tag)) {
                flag = true;
            }
        }

        // 检查当前tag是否重复
        if (flag) {
            // 记录且不导入
            tags.append(tag).append(",");
        } else {
            // 插入到数据库
            AssetComputer assetComputer = new AssetComputer();
            BeanUtils.copyProperties(assetComputerImportVO, assetComputer);
            assetComputer.setUserId(userId);
            assetComputer.setCreateBy(SecurityUtils.getUserId());
            assetComputerService.save(assetComputer);
            successCount++;
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
